package com.ben.smm.util;

import java.text.SimpleDateFormat;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.ben.smm.domain.Sms;

public class SmsDBHelper extends SQLiteOpenHelper {
	private final static String DATABASE_NAME = "smm_db";
	private static int DATABASE_VERSION = 1;
	private final static String TABLE_NAME = "sms";
	private final static String SMS_ID = "sms_id";
	private final static String TYPE = "type";
	private final static String PHONE_NUMBER = "phone_number";
	private final static String CONTENT = "content";
	private final static String SMS_DATETIME = "sms_date";

	public SmsDBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "create table if not exists " + TABLE_NAME + "("
				+ SMS_ID + " integer primary key autoincrement," + TYPE
				+ " varchar," + PHONE_NUMBER + " varchar," + CONTENT
				+ " text," + SMS_DATETIME + " datetime);";
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String sql = "drop table if exists " + TABLE_NAME;
		db.execSQL(sql);
		DATABASE_VERSION = newVersion;
		onCreate(db);
	}

	public Cursor select() {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null,
				" _id desc");
		return cursor;
	}

	public long insert(Sms sms) {
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(TYPE, sms.getType());
		cv.put(PHONE_NUMBER, sms.getPhone_number());
		cv.put(CONTENT, sms.getContent());
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		String receive_datetime = simpleDateFormat
				.format(sms.getSms_date());
		cv.put(SMS_DATETIME, receive_datetime);
		long row = db.insert(TABLE_NAME, null, cv);
		return row;
	}

	public void delete(int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		String where = TYPE + "=?";
		String[] whereValue = { Integer.toString(id) };
		db.delete(TABLE_NAME, where, whereValue);
	}

	public void update(int id, String Title) {
		SQLiteDatabase db = this.getWritableDatabase();
		String where = TYPE + "=?";
		String[] whereValue = { Integer.toString(id) };
		ContentValues cv = new ContentValues();
		cv.put(SMS_DATETIME, Title);
		db.update(TABLE_NAME, cv, where, whereValue);
	}

}